package com.yinkgh.mybatis.controller;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.yinkgh.mybatis.view.BondTrialInfoView;
import com.yinkgh.util.ExcelUtil;

@Controller
@RequestMapping("/download")
public class DownloadController {

	
	@RequestMapping("/export")
	@ResponseBody
	public String exportExcel(HttpServletRequest request, HttpServletResponse response) {
		String data = request.getParameter("data");
		System.out.println(data);
		
		try {
			List<BondTrialInfoView> bondTrialInfoViews = ExcelUtil.getData();
			Workbook workbook = ExcelUtil.getInstance().exportExcel(bondTrialInfoViews, ExcelUtil.TYPE_XLS);
			
			SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmmsss");
			String filename = sdf.format(new Date()) + ".xls";
			// 设置文件MIME类型
			response.reset(); // 必要地清除response中的缓存信息
			
			response.setContentType(request.getServletContext().getMimeType(filename));
//			response.setContentType("application/octet-stream");  
			response.setContentType("application/msexcel;charset=utf-8");  
	        response.setHeader("name", filename);  
	        response.setHeader("Cache-Control", "must-revalidate, post-check=0, pre-check=0");  
	        response.setHeader("Pragma", "public");  
	        response.setDateHeader("Expires", 0); 
	        response.setHeader("Content-disposition","attachment; filename=\""+URLEncoder.encode(filename, "UTF-8")+ "\"");
			//网络下载代码
			
			workbook.write(response.getOutputStream());
			response.getOutputStream().flush();
			response.getOutputStream().close();
			
			
			
			
			
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return null;
	}
}
